/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com, guwei8576431@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE 
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 * 
 * Created on 2009-11-8
 *******************************************************************************/

package org.cgtw.scriptprofile.widget;

import java.io.File;
import java.io.IOException;

import javax.swing.JRootPane;
import javax.swing.text.BadLocationException;

import org.apache.commons.io.FileUtils;
import org.cgtw.scriptprofile.engine.manager.CharsetDetector;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.RTextScrollPane;

public class ResourceEditor extends JRootPane{
	private RTextScrollPane scrollPane;

	private RSyntaxTextArea textArea;

	private String contextType;

	private String filePath;

	private Gutter gutter;

	public ResourceEditor(String contextType) {
		this.contextType = contextType;
		init();
	}

	public void init() {
		textArea = createTextArea();
		scrollPane = new RTextScrollPane(textArea);
		gutter = scrollPane.getGutter();
		getContentPane().add(scrollPane);
	}

	private RSyntaxTextArea createTextArea() {
		RSyntaxTextArea textArea = new RSyntaxTextArea();
		textArea.setSyntaxEditingStyle(this.getContextType());
		textArea.setCaretPosition(0);
		textArea.setEditable(false);
		textArea.requestFocusInWindow();
		textArea.setMarkOccurrences(true);
		textArea.setWrapStyleWord(false);
		return textArea;
	}

	public String getText() {
		return textArea.getText();
	}

	public void setText(String text) {
		textArea.setText(text);
	}

	public void openFile(File file) {
		filePath = file.getAbsolutePath();
		String fileContent;
		try {
			CharsetDetector detector = new CharsetDetector();
			detector.detect(file);
			String encoding = detector.getCharset();
			fileContent = FileUtils.readFileToString(file, encoding);
			setText(fileContent);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFilePath() {
		return filePath;
	}

	public void focus(int line) {
		int offset;
		try {
			offset = textArea.getLineEndOffset(line - 2);
			if (offset > 0) {
				textArea.setCaretPosition(offset);
			}
		} catch (BadLocationException e) {
			e.printStackTrace();
		}

	}

	public String getContextType() {
		return contextType;
	}

	public void setContextType(String contextType) {
		this.contextType = contextType;
	}

}

